#!/usr/bin/env python3

"""Simple HTTP Server With Upload.
python -V3.6
This module builds on http.server by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
"""

__version__ = "0.1"
__all__ = ["SimpleHTTPRequestHandler"]
__author__ = "清纯世纪"
__home_page__ = "https://blog.csdn.net/qq_45100200/article/details/132343498"

import hashlib
import os, sys
import os.path, time
import posixpath
import http.server
import socketserver
import html
import shutil
import mimetypes
import re
import argparse
import base64
import urllib.parse
import datetime
import shutil

from io import BytesIO

USERNAME = 'admin'
PASSWORD = 'jw@2023!yy'
algorithm = "MD5"  # SHA-256, MD5

AUTH_KEY = base64.b64encode('{}:{}'.format(USERNAME, PASSWORD).encode()).decode()


def jm_md5(password):
    m = hashlib.md5()  # 构建MD5对象
    m.update(password.encode(encoding='utf-8'))  # 设置编码格式 并将字符串添加到MD5对象中
    password_md5 = m.hexdigest()  # hexdigest()将加密字符串 生成十六进制数据字符串值
    return password_md5


def get_dict_from_str(str, split=","):
    # print(str)
    auth_str = str.replace("\"", "").replace(" ", "")
    auth_list = auth_str.split(split)
    auth_dict = {}
    for it in auth_list:
        it_list = it.split("=")
        if len(it_list) > 1:
            auth_dict[it_list[0]] = it.replace(it_list[0] + "=", "")
    return auth_dict


def get_response_str(auth_dict, user, pwd):
    uri = auth_dict["uri"]
    nc = auth_dict["nc"]
    cn_once = auth_dict["cnonce"]
    n_once = auth_dict["nonce"]
    realm = auth_dict["realm"]
    qop = auth_dict["qop"]
    method = auth_dict["method"]
    a1 = f"{user}:{realm}:{pwd}"
    a2 = f"{method}:{uri}"
    ha1 = jm_md5(a1)
    ha2 = jm_md5(a2)
    response_str = f"{ha1}:{n_once}:{nc}:{cn_once}:{qop}:{ha2}"
    # print(response_str)
    response_str = jm_md5(response_str)
    return response_str


def del_with_cmd(path):
    try:
        if os.path.isdir(path):
            cmd = 'del "' + path + '" /F'
            print(cmd)
            os.system(cmd)
    except Exception as e:
        print(e)


def fbytes(B):
    'Return the given bytes as a human friendly KB, MB, GB, or TB string'
    B = float(B)
    KB = float(1024)
    MB = float(KB ** 2)  # 1,048,576
    GB = float(KB ** 3)  # 1,073,741,824
    TB = float(KB ** 4)  # 1,099,511,627,776

    if B < KB:
        return '{0} {1}'.format(B, 'Bytes' if 0 == B > 1 else 'Byte')
    elif KB <= B < MB:
        return '{0:.2f} KB'.format(B / KB)
    elif MB <= B < GB:
        return '{0:.2f} MB'.format(B / MB)
    elif GB <= B < TB:
        return '{0:.2f} GB'.format(B / GB)
    elif TB <= B:
        return '{0:.2f} TB'.format(B / TB)


class SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    """Simple HTTP request handler with GET/HEAD/POST commands.
    This serves files from the current directory and any of its
    subdirectories.  The MIME type for files is determined by
    calling the .guess_type() method. And can reveive file uploaded
    by client.
    The GET/HEAD/POST requests are identical except that the HEAD
    request omits the actual contents of the file.
    """

    server_version = "SimpleHTTPWithUpload/" + __version__

    def get_resp(self, method):
        auth_string = self.headers.get("Authorization")
        if auth_string is not None:
            auth_dict = get_dict_from_str(self.headers.get("Authorization")[7:])
            auth_dict["method"] = method
            response_str = get_response_str(auth_dict, USERNAME, PASSWORD)
            # print(auth_dict, response_str)
            if auth_dict["response"] == response_str:
                return True
            else:
                return False
        else:
            return None

    def _delete_file(self, source):
        os.remove(source)

    def do_GET(self):
        # print(self.headers.get("Authorization"))
        status = self.get_resp("GET")
        """ Present frontpage with user authentication. """
        if status is None:
            self.do_AUTHHEAD()
            self.wfile.write(b"no auth header received")
        elif status is True:
            """Serve a GET request."""
            f = self.send_head()
            if f:
                self.copyfile(f, self.wfile)
                f.close()
        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.headers.get("Authorization").encode())
            self.wfile.write(b"not authenticated")

    def do_HEAD(self):
        status = self.get_resp("HEAD")
        """ Present frontpage with user authentication. """
        if status is None:
            self.do_AUTHHEAD()
            self.wfile.write(b"no auth header received")
        elif status is True:
            """Serve a HEAD request."""
            f = self.send_head()
            if f:
                f.close()
        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.headers.get("Authorization").encode())
            self.wfile.write(b"not authenticated")

    def do_AUTHHEAD(self):
        self.send_response(401)
        self.send_header("WWW-Authenticate", f'''Digest
        realm="http-auth@example.org",
        qop="auth, auth-int",
        algorithm={algorithm},
        nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v",
        opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS''')
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.end_headers()

    def do_DELETE(self):
        datas = self.rfile.read(int(self.headers['content-length']))
        name = urllib.parse.unquote(datas.decode("utf-8"))
        params = get_dict_from_str(name, "&")
        name = params["name"]
        folder = params["folder"]
        status = self.get_resp("DELETE")
        """ Present frontpage with user authentication. """
        if status is None:
            self.do_AUTHHEAD()
            self.wfile.write(b"no auth header received")
        elif status is True:
            """Serve a POST request."""
            # f = self.send_head()
            f = BytesIO()
            path = self.translate_path(self.path)
            path = path + name
            if name != "":
                try:
                    print(os.path.isdir(path))
                    if folder == "1":
                        # print(path)
                        os.rmdir(path)
                        # try:
                        #     shutil.rmtree(path)
                        # except OSError:
                        #     del_with_cmd(path)
                    else:
                        self._delete_file(path)

                    # 准备要返回的 JSON 数据
                    f.write(b'{"code": 200,"data": "SUCCESS","msg": "has deleted"}')
                    # self.wfile.write(json.dumps(data).encode())
                    # 设置响应头
                    self.send_response(200)
                    self.send_header("Content-Type", "application/json")
                    self.end_headers()
                except OSError as error:
                    print(error)
                    # 准备要返回的 JSON 数据
                    f.write(b'{"code": 500,"data": "FAILED","msg": "has no deleted"}')
                    self.send_response(500)
                    self.send_header("Content-Type", "application/json")
                    self.end_headers()
                finally:
                    length = f.tell()
                    f.seek(0)
                    self.send_header("Content-Length", str(length))
                    if f:
                        self.copyfile(f, self.wfile)
                        f.close()
        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.headers.get("Authorization").encode())
            self.wfile.write(b"not authenticated")

    def do_PUT(self):
        datas = self.rfile.read(int(self.headers['content-length']))
        name = datas.decode("utf-8").replace("dir=", "")
        # name = urllib.parse().unquote(name)
        name = urllib.parse.unquote(name)
        status = self.get_resp("PUT")
        """ Present frontpage with user authentication. """
        if status is None:
            self.do_AUTHHEAD()
            self.wfile.write(b"no auth header received")
        elif status is True:
            """Serve a POST request."""
            # f = self.send_head()
            f = BytesIO()
            path = self.translate_path(self.path)
            path = f"{path}/{name}"
            print(path)
            if name != "":
                try:
                    if not os.path.exists(path):
                        os.makedirs(path)
                    # 准备要返回的 JSON 数据
                    f.write(b'{"code": 200,"data": "SUCCESS","msg": "has created"}')
                    # self.wfile.write(json.dumps(data).encode())
                    # 设置响应头
                    self.send_response(200)
                    self.send_header("Content-Type", "application/json")
                    self.end_headers()
                except OSError as error:
                    # 准备要返回的 JSON 数据
                    f.write(('{"code": 500,"data": "FAILED","msg": "has no created,because %s"}' % error).encode())
                    self.send_response(500)
                    self.send_header("Content-Type", "application/json")
                    self.end_headers()
                finally:
                    length = f.tell()
                    f.seek(0)
                    self.send_header("Content-Length", str(length))
                    if f:
                        self.copyfile(f, self.wfile)
                        f.close()
        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.headers.get("Authorization").encode())
            self.wfile.write(b"not authenticated")

    def do_POST(self):
        status = self.get_resp("POST")
        """ Present frontpage with user authentication. """
        if status is None:
            self.do_AUTHHEAD()
            self.wfile.write(b"no auth header received")
        elif status is True:
            """Serve a POST request."""
            r, info = self.deal_post_data()
            print((r, info, "by: ", self.client_address))
            f = BytesIO()
            f.write(b'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
            f.write("<html>\n<meta charset=\"UTF-8\">\n<title>文件管理</title>\n".encode())
            f.write(b'<link rel="stylesheet" type="text/css" href="/source/layui/css/layui.css">\n')
            f.write(b'<style type="text/css">\n')
            f.write(b'* {font-family: Helvetica; font-size: 16px; }\n')
            f.write(b'a { text-decoration: none; }\n')
            f.write(b'</style>\n')
            f.write("<body style='padding:10px;'>\n<h2>上传结果</h2>\n".encode())
            f.write(b"<hr>\n")
            if r:
                f.write("<strong>上传成功!</strong>".encode())
            else:
                f.write("<strong>上传失败!</strong>".encode())
            f.write(info.encode())
            f.write(("<br><br><a href=\"%s\">" % self.headers['referer']).encode())
            f.write("<button class=\"layui-btn layui-btn-sm\">返回</button></a>\n".encode())
            # f.write(b"<hr><small>Powered By: bones7456<br>Check new version ")
            # f.write(b"<a href=\"https://gist.github.com/UniIsland/3346170\" target=\"_blank\">")
            f.write(b"</a></small></body>\n</html>\n")
            length = f.tell()
            f.seek(0)
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(length))
            self.end_headers()
            if f:
                self.copyfile(f, self.wfile)
                f.close()
        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.headers.get("Authorization").encode())
            self.wfile.write(b"not authenticated")

    def deal_post_data(self):
        uploaded_files = []
        content_type = self.headers['content-type']
        if not content_type:
            return False, "Content-Type header doesn't contain boundary"
        boundary = content_type.split("=")[1].encode()
        remainbytes = int(self.headers['content-length'])
        line = self.rfile.readline()
        remainbytes -= len(line)
        if not boundary in line:
            return False, "Content NOT begin with boundary"
        while remainbytes > 0:
            line = self.rfile.readline()
            remainbytes -= len(line)
            fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line.decode())
            if not fn:
                return False, "Can't find out file name..."
            path = self.translate_path(self.path)
            fn = os.path.join(path, fn[0])
            print(f"fn:{fn}")
            line = self.rfile.readline()
            remainbytes -= len(line)
            line = self.rfile.readline()
            remainbytes -= len(line)
            try:
                out = open(fn.replace(" ", "_"), 'wb')
            except IOError:
                return False, "<br><br>你确定有权限上传文件吗?"
            else:
                with out:
                    preline = self.rfile.readline()
                    remainbytes -= len(preline)
                    while remainbytes > 0:
                        line = self.rfile.readline()
                        remainbytes -= len(line)
                        if boundary in line:
                            preline = preline[0:-1]
                            if preline.endswith(b'\r'):
                                preline = preline[0:-1]
                            out.write(preline)
                            uploaded_files.append(fn)
                            break
                        else:
                            out.write(preline)
                            preline = line
        return (True, "<br><br>'%s'" % "'<br>'".join(uploaded_files))

    def send_head(self):
        """Common code for GET and HEAD commands.
        This sends the response code and MIME headers.
        Return value is either a file object (which has to be copied
        to the outputfile by the caller unless the command was HEAD,
        and must be closed by the caller under all circumstances), or
        None, in which case the caller has nothing further to do.
        """
        path = self.translate_path(self.path)
        f = None
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # redirect browser - doing basically what apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                self.end_headers()
                return None
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    path = index
                    break
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            # Always read in binary mode. Opening files in text mode may cause
            # newline translations, making the actual size of the content
            # transmitted *less* than the content-length!
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        self.end_headers()
        return f

    def list_directory(self, path):
        """Helper to produce a directory listing (absent index.html).
        Return value is either a file object, or None (indicating an
        error).  In either case, the headers are sent, making the
        interface the same as for send_head().
        """
        try:
            list = os.listdir(path)
        except os.error:
            self.send_error(404, "No permission to list directory")
            return None
        enc = sys.getfilesystemencoding()
        list.sort(key=lambda a: a.lower())
        f = BytesIO()
        displaypath = html.escape(urllib.parse.unquote(self.path))
        f.write(b'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
        f.write(b'<html>\n<meta charset=\"UTF-8\">\n')
        f.write(('<meta http-equiv="Content-Type" '
                 'content="text/html; charset=%s">' % enc).encode(enc))
        f.write(("<title>文件管理 %s</title>\n" % displaypath).encode(enc))
        f.write(b'<style type="text/css">\n')
        f.write(b'* {font-family: Helvetica; font-size: 16px; }\n')
        f.write(b'a { text-decoration: none; }\n')
        f.write(b'a:link { text-decoration: none; font-weight: bold; color: #0000ff; }\n')
        f.write(b'a:visited { text-decoration: none; font-weight: bold; color: #0000ff; }\n')
        f.write(b'a:active { text-decoration: none; font-weight: bold; color: #0000ff; }\n')
        f.write(b'a:hover { text-decoration: none; font-weight: bold; color: #ff0000; }\n')
        f.write(b'table {\n  border-collapse: separate;\n}\n')
        f.write(b'th, td {\n  padding:2px 10px !important;border-left:0 !important;border-right:0 !important;\n}\n')
        f.write(b'td span {\n  vertical-align:middle;margin-left:3px;\n}\n')
        f.write(b'td img {\n  vertical-align:middle;\n}\n')
        f.write(b'</style>\n')
        f.write(b'<link rel="stylesheet" type="text/css" href="/source/layui/css/layui.css">\n')
        f.write(b'<script type="text/javascript" src="/source/jquery-3.2.1.min.js"></script>\n')
        f.write(b'<script type="text/javascript" src="/source/layui/layui.js"></script>\n')
        f.write(b'<script type="text/javascript" src="/source/delete.js"></script>\n')
        f.write(b'<body style="padding:10px;">\n')
        f.write(b"<div style=\"height:10px;\"></div>\n")
        f.write(b"<form ENCTYPE=\"multipart/form-data\" method=\"post\" style='overflow: hidden;' onsubmit=\"return checkFile()\">")
        f.write(b"<input class='layui-btn layui-btn-sm' name=\"file\" type=\"file\" multiple style=\"box-shadow: 0 0 1px 1px #767676 inset;width:500px;margin-left: -75px;\" />")
        f.write(("<input class='layui-btn layui-btn-sm' type=\"submit\" value=\"上传\" style=\"margin-left: 5px;\" /><span class='layui-btn layui-btn-sm' style=\"margin-left: 5px;\" onclick='create_folder(\"%s\");'>创建文件夹</span></form>\n" % displaypath).encode(
            enc))
        f.write(b"<hr>\n")
        f.write(b'<table class="layui-table" style="width:auto;min-width:50%;">\n')
        f.write(('<tr><td style="width:66px;" colspan="5"><a href="../" ><img src="" alt="[PARENTDIR]" width="24" height="24" style="vertical-align:middle;"><span style="vertical-align:middle;margin-left:10px;">返回</span></a><span style="margin-left:10px;">%s</span></td></tr>\n' % displaypath).encode(
            enc))
        f.write(('<tr><td>名称</td><td>修改日期</td><td>类型</td><td>大小</td><td></td></tr>\n').encode(enc))
        for name in list:
            dirimage = ''
            fullname = os.path.join(path, name)
            displayname = linkname = name
            fsize = fbytes(os.path.getsize(fullname))
            # created_date = time.ctime(os.path.getmtime(fullname))
            dt = datetime.datetime.fromtimestamp(os.path.getmtime(fullname))
            created_date = dt.strftime("%Y/%m/%d %H:%M")
            xd_path = displaypath + name
            file_ext = os.path.splitext(name)[1][1:]
            file_ext = file_ext.upper() + " 文件"
            file_count = 0
            # Append / for directories or @ for symbolic links
            if os.path.isdir(fullname):
                dirimage = ''
                displayname = name
                linkname = name + "/"
                fsize = ''
                file_count = len(os.listdir(fullname))
            if os.path.islink(fullname):
                dirimage = ''
                displayname = name + "@"
            if name.endswith(('.bmp', '.gif', '.jpg', '.png')):
                dirimage = name
            if name.endswith(('.avi', '.mpg')):
                dirimage = ''
            if name.endswith(('.idx', '.srt', '.sub')):
                dirimage = ''
            if name.endswith('.iso'):
                dirimage = ''
                # Note: a link to a directory displays with @ and links with /
            if name.endswith(('.js', '.css', 'source')):
                continue
            if os.path.isdir(fullname):
                if file_count == 0 and False:
                    f.write(('<tr><td><a href="%s"><img src="%s" width="24" height="24"><span>%s</span></a></td><td style="font-weight: bold;">%s</td><td>文件夹</td><td style="font-weight: bold;">%s</td><td><a href="javascript:void(0);" style="color:red;" onclick="del(\'%s\',1)">删除</a></td></tr>\n'
                                        % (urllib.parse.quote(linkname), dirimage, html.escape(displayname), created_date, fsize, xd_path)).encode(enc))
                else:
                    f.write(('<tr><td><a href="%s"><img src="%s" width="24" height="24"><span>%s</span></a></td><td style="font-weight: bold;">%s</td><td>文件夹</td><td style="font-weight: bold;">%s</td><td></td></tr>\n'
                                        % (urllib.parse.quote(linkname), dirimage, html.escape(displayname), created_date, fsize)).encode(enc))
            else:
                f.write((
                                    '<tr><td><a href="%s"><img src="%s" width="24" height="24"><span>%s</span></a></td><td style="font-weight: bold;">%s</td><td>%s</td><td style="font-weight: bold;">%s</td><td><a href="javascript:void(0);" style="color:red;" onclick="del(\'%s\',0)">删除</a></td></tr>\n'
                                    % (urllib.parse.quote(linkname), dirimage, html.escape(displayname), created_date,
                                       file_ext, fsize, xd_path)).encode(enc))
        f.write(b"</table>\n</body>\n</html>\n")
        length = f.tell()
        f.seek(0)
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-Length", str(length))
        self.end_headers()
        return f

    def translate_path(self, path):
        """Translate a /-separated PATH to the local filename syntax.
        Components that mean special things to the local file system
        (e.g. drive or directory names) are ignored.  (XXX They should
        probably be diagnosed.)
        """
        # abandon query parameters
        path = path.split('?', 1)[0]
        path = path.split('#', 1)[0]
        path = posixpath.normpath(urllib.parse.unquote(path))
        words = path.split('/')
        words = [_f for _f in words if _f]
        path = os.getcwd()
        for word in words:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir, os.pardir): continue
            path = os.path.join(path, word)
        return path

    def copyfile(self, source, outputfile):
        """Copy all data between two file objects.
        The SOURCE argument is a file object open for reading
        (or anything with a read() method) and the DESTINATION
        argument is a file object open for writing (or
        anything with a write() method).
        The only reason for overriding this would be to change
        the block size or perhaps to replace newlines by CRLF
        -- note however that this the default server uses this
        to copy binary data as well.
        """
        shutil.copyfileobj(source, outputfile)

    def guess_type(self, path):
        """Guess the type of a file.
        Argument is a PATH (a filename).
        Return value is a string of the form type/subtype,
        usable for a MIME Content-type header.
        The default implementation looks the file's extension
        up in the table self.extensions_map, using application/octet-stream
        as a default; however it would be permissible (if
        slow) to look inside the data to make a better guess.
        """

        base, ext = posixpath.splitext(path)
        if ext in self.extensions_map:
            return self.extensions_map[ext]
        ext = ext.lower()
        if ext in self.extensions_map:
            return self.extensions_map[ext]
        else:
            return self.extensions_map['']

    if not mimetypes.inited:
        mimetypes.init()  # try to read system mime.types
    extensions_map = mimetypes.types_map.copy()
    extensions_map.update({
        '': 'application/octet-stream',  # Default
        '.py': 'text/plain',
        '.c': 'text/plain',
        '.h': 'text/plain',
    })


def get_local_ip():
    import socket
    """
    获取本机IP地址
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
                        help='Specify alternate bind address '
                             '[default: all interfaces]')
    parser.add_argument('port', action='store',
                        default=666, type=int,
                        nargs='?',
                        help='Specify alternate port [default: 8000]')
    args = parser.parse_args()

    PORT = args.port
    BIND = args.bind
    HOST = BIND

    if HOST == '':
        HOST = 'localhost'

    Handler = SimpleHTTPRequestHandler

    with socketserver.TCPServer((BIND, PORT), Handler) as httpd:
        serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
        print(serve_message.format(host=HOST, port=PORT))
        print("请输入以下地址进行文件传输：http://{}:{}".format(get_local_ip(), PORT))
        httpd.serve_forever()
